#include "temperature.h" 

uint8 readSensorData(void)  
{  
	uint8 crc;   
	uint8 i;  

	pinMode(DHT11PIN,OUTPUT); // set mode to output  
	digitalWrite(DHT11PIN, 0); // output a high level   
	delay(25);  
	digitalWrite(DHT11PIN, 1); // output a low level   
	pinMode(DHT11PIN, INPUT); // set mode to input  
	pullUpDnControl(DHT11PIN,PUD_UP);  

	delayMicroseconds(27);  
	if(digitalRead(DHT11PIN)==0) //SENSOR ANS  
	{  
		while(!digitalRead(DHT11PIN)); //wait to high  

		for(i=0;i<32;i++)  
		{  
			while(digitalRead(DHT11PIN)); //data clock start  
			while(!digitalRead(DHT11PIN)); //data start  
			delayMicroseconds(HIGH_TIME);  
			databuf*=2;  
			if(digitalRead(DHT11PIN)==1) //1  
			{  
				databuf++;  
			}  
		}  

		for(i=0;i<8;i++)  
		{  
			while(digitalRead(DHT11PIN)); //data clock start  
			while(!digitalRead(DHT11PIN)); //data start  
			delayMicroseconds(HIGH_TIME);  
			crc*=2;    
			if(digitalRead(DHT11PIN)==1) //1  
			{  
				crc++;  
			}  
		}  
		return 1;  
	}  
	else  
	{  
		return 0;  
	}  
}  

int get_env_temp(int * temp, int * rh){
	int rh_int = 0, rh_dec = 0;
	int tmp_int = 0, tmp_dec = 0;

	if (-1 == wiringPiSetup()) {  
		DEBUG("Setup wiringPi failed!");  
		return 1;  
	}  

	pinMode(DHT11PIN, OUTPUT); // set mode to output  
	digitalWrite(DHT11PIN, 1); // output a high level   

	DEBUG("________DHT11PIN___________");  
	pinMode(DHT11PIN,OUTPUT); // set mode to output  
	digitalWrite(DHT11PIN, 1); // output a high level   

	delay(3000);

	if(readSensorData())  
	{  
		rh_int = (databuf>>24)&0xff;
		rh_dec = (databuf>>16)&0xff;
		*rh = rh_int;
		DEBUG("RH:%d.%d",rh_int, rh_dec);
		tmp_int = (databuf>>8)&0xff;
		tmp_dec = databuf&0xff;
		*temp = tmp_int;
		DEBUG("TMP:%d.%d",tmp_int, tmp_dec);
		databuf=0;  
	}  
	else  
	{  
		DEBUG("Sorry! Sensor dosent ans!\n");  
		databuf=0;  
		*rh = 255;
		*temp = 255;
		return 1;
	}  
	return 0;
}

#if 0
int main (void)  
{  
	int rh_int = 0, rh_dec = 0;
	int tmp_int = 0, tmp_dec = 0;
	DEBUG("Use GPIO1 to read data!\n");  

	if (-1 == wiringPiSetup()) {  
		DEBUG("Setup wiringPi failed!");  
		return 1;  
	}  

	pinMode(DHT11PIN, OUTPUT); // set mode to output  
	digitalWrite(DHT11PIN, 1); // output a high level   

	DEBUG("________DHT11PIN___________");  
	pinMode(DHT11PIN,OUTPUT); // set mode to output  
	digitalWrite(DHT11PIN, 1); // output a high level   
	delay(3000);  
	if(readSensorData())  
	{  
		rh_int = (databuf>>24)&0xff;
		rh_dec = (databuf>>16)&0xff;
		printf("RH:%d.%d\n",rh_int, rh_dec);
		tmp_int = (databuf>>8)&0xff;
		tmp_dec = databuf&0xff;
		printf("TMP:%d.%d\n",tmp_int, tmp_dec);
		databuf=0;  
	}  
	else  
	{  
		DEBUG("Sorry! Sensor dosent ans!\n");  
		databuf=0;  
	}  
	return 0;  
}  
#endif

